package com.opennews.openplatform.filter;

import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Moved calling auth-service to data-aggregator-service.
 *
 * IMPORTANT!!!
 *
 * @Order(1) matters here because calling other services via http won't work without it.
 */
@Order(1)
@RequiredArgsConstructor
@Component
public class MyGlobalFilter implements GlobalFilter {
    private final RestTemplate restTemplate;
    private final WebClient.Builder webClientBuilder;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //        ServerHttpRequest request = exchange.getRequest();
        //        String resourceUri = request.getURI().getPath();
        //        String authorizationHeader = request.getHeaders().getFirst("authorization");
        //
        //        CheckPermissionDto checkPermissionDto = new CheckPermissionDto();
        //        checkPermissionDto.setResourceUri(resourceUri);
        //        checkPermissionDto.setAuthorizationHeader(authorizationHeader);
        //        checkPermissionDto.setHttpMethod(request.getMethod().name());
        //
        //        // Create the request to the auth-service with headers and resource URI
        //        return webClientBuilder.build()
        //                .post()
        //                .uri("lb://auth-service/api/auth/permissions/check")
        //                .bodyValue(checkPermissionDto)
        //                .retrieve()
        //                .bodyToMono(Boolean.class)
        //                .onErrorResume(e -> Mono.just(false))
        //                .flatMap(hasPermission -> {
        //                    if (!hasPermission) {
        //                        // If permission check fails, reject the request.
        //                        ServerHttpResponse response = exchange.getResponse();
        //                        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //
        //                        return response.setComplete();
        //                    }
        //
        //                    // If permission check passes, continue with the request.
        //                    return chain.filter(exchange);
        //                });

        return chain.filter(exchange);
    }
}
